<?php

namespace App\Kuafu\Order\Service;

use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Model\ConsumerOrder;
use App\Kuafu\Order\Model\OrderDetailSplitModel;
use App\Kuafu\Order\Model\OrderSplitModel;
use App\Kuafu\Shop\Service\ShopService;

class ConsumerOrderService extends BaseService
{

    /**
     * 获取用户订单列表
     *
     * @param $userId
     * @param $pageSize
     * @param $pageNum
     * @param $shopId
     * @param int $flagComplain
     * @return array
     */
    public static function getUserAllOrderList(
        $userId,
        $userUnionid,
        $pageSize,
        $pageNum,
        $shopId,
        $flagComplain = CodeEnum::ORDER_STATUS_DEFAULT
    ) {
        $orderLists = ConsumerOrder::getUserAllOrderList($userId, $userUnionid, $pageSize, $pageNum, $flagComplain);
        $orderList  = $orderLists->items();
        //查询店铺信息
        $shopIds  = array_unique(array_column($orderList, 'shopId'));
        $shopList = ShopService::getShopListByShopIds($shopIds);
        $shopList = $shopList->keyBy("id")->toArray();
        //组装数据
        $returnData = [];
        foreach ($orderList as $value) {
            $combineData['orderId']     = (string)$value['orderId'];
            $combineData['createdAt']   = $value['createdAt']->toDateTimeString();
            $combineData['orderStatus'] = CodeEnum::STATUS_CODE_TEXT[$value['orderStatus'] ?: 0];
            if ($value['orderStatus'] == CodeEnum::ORDER_STATUS_REVERSE) {
                $combineData['orderStatus'] = CodeEnum::STATUS_CODE_TEXT[CodeEnum::ORDER_STATUS_FINISHED];
            }
            if ($value['originalPrice'] == 0) {
                $combineData['orderStatus'] = '已退款';
            }
            $combineData['shopName']    = $shopList[$value['shopId']]['name']?? '';
            $combineData['shortName']   = $shopList[$value['shopId']]['shortName'] ?? '';
            $combineData['shopId']      = $value['shopId'];
            $combineData['payPrice']    = $value['payPrice'];
            $combineData['shouldPrice'] = $value['orderShouldPrice'];
            $combineData['count']       = $value['count'];

            $imageList = explode(',', $value['images']);
            $imageList = array_filter($imageList);
            array_walk($imageList, function (&$item) {
                $item = CommonService::joinImageUrl($item);
            });
            $combineData['imageList'] = array_slice($imageList, 0, 3);
            $returnData[]             = $combineData;
        }

        $return['pageNum']  = $orderLists->currentPage();
        $return['pageSize'] = $orderLists->perPage();
        $return['count']    = $orderLists->total();
        $return['list']     = array_values($returnData);
        return $return;
    }

}
